import 'dart:convert';
import 'dart:io';

import 'package:dio/dio.dart';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:path_provider/path_provider.dart';
import 'package:seedfour/app/constants.dart';
import 'package:seedfour/app/routes/app_routes.dart';
import 'package:seedfour/app/theme.dart';
import 'package:seedfour/app/views/module_seal/seal_create/logic.dart';
import 'package:seedfour/toolkit/typedef/function.dart';

import '../../../models/case_detail_entity.dart';
import '../../../models/case_invoice_entity.dart';
import '../../../models/case_order_info_entity.dart';
import '../../../models/raw_data.dart';
import '../../../services/api_service.dart';
import '../../../services/common_service.dart';
import 'state.dart';

class CaseDetailLogic extends GetxController {
  final CaseDetailState state = CaseDetailState();

  final apiService = Get.find<ApiService>();
  final commonService = Get.find<CommonService>();

  late String id;

  @override
  void onInit() {
    super.onInit();

    id = Get.arguments;

    _getCaseInfo(id);
  }

  // 下载附件
  void downloadFile(int fileIndex) async {
    var file = state.caseContractList[fileIndex];

    EasyLoading.show(status: '文件下载中...');

    Directory? appDocDir = await getDownloadsDirectory();
    String savePath = '${appDocDir!.path}/${file.name}';

    RawData? result = await apiService.download(
        file.id!, state.caseDetail.value!.caseInfo!.id!);
    if (result != null) {
      var url = result.value['data']['tempPath'];
      final response = await Dio().download(url, savePath);

      if (response.statusCode == 200) {
        EasyLoading.showToast('文件已保存到：$savePath',
            duration: const Duration(seconds: 6));
      } else {
        EasyLoading.showToast('下载失败');
      }
    }
  }

  void deleteFile(int fileIndex) async {
    var file = state.caseContractList[fileIndex];

    EasyLoading.show(status: '文件删除中...');

    RawData? result = await apiService.deleteFile(
        file.id!, state.caseDetail.value!.caseInfo!.id!);
    if (result != null) {
      EasyLoading.showToast('文件已删除');
      state.caseContractList.removeAt(fileIndex);
    } else {
      EasyLoading.showToast('删除失败');
    }
  }

  void uploadContract() async {
    var files = (await FilePicker.platform.pickFiles(
      type: FileType.any,
      allowMultiple: true,
    ))
        ?.files;

    if (files != null && files.isNotEmpty) {
      EasyLoading.show(status: '合同上传中...', dismissOnTap: true);
      for (var path in files) {
        RawData? result = await apiService.fileUpload(
          action: 'upload-contract',
          fileIndex: 6401,
          filePath: path.path!,
          caseId: id,
        );

        if (result == null) {
          EasyLoading.dismiss();
          EasyLoading.showError('合同上传失败');
          return;
        }
      }

      _getCaseInfo(id);
      EasyLoading.dismiss();
      Get.snackbar('提示', '合同上传成功');
    }
  }

  void toApplySeal() {
    Get.toNamed(RouteGet.sealCreate,
        arguments: SealCreateParams(
          sealPaperType: SealPaperType.contract,
          caseId: state.caseDetail.value!.caseInfo!.id,
          caseName: state.caseDetail.value!.caseInfo!.caseNameStr,
        ));
  }

  // 获取可关联收款订单列表
  void getCaseIncomeOrders(ParamVoidCallback callback) {
    EasyLoading.show();

    apiService
        .getCaseOrderList('order', id, state.incomeOrderStartTime.value,
            state.incomeOrderEndTime.value, 4)
        .then((value) {
      EasyLoading.dismiss();
      if (value == null) {
        Get.snackbar('提示', '获取收款订单失败');
      } else {
        state.unselectIncomeOrders.clear();
        state.unselectIncomeOrders.addAll(value.userOrderList ?? []);
        EasyLoading.dismiss();
        callback();
      }
    });
  }

  // 获取可关联付款订单列表
  void getCasePaidOrders(ParamVoidCallback callback) {
    EasyLoading.show();

    apiService
        .getCaseOrderList('order', id, state.paidOrderStartTime.value,
            state.paidOrderEndTime.value, 6)
        .then((value) {
      EasyLoading.dismiss();
      if (value == null) {
        Get.snackbar('提示', '获取付款订单失败');
      } else {
        state.unselectPaidOrders.clear();
        state.unselectPaidOrders.addAll(value.userOrderList ?? []);
        EasyLoading.dismiss();
        callback();
      }
    });
  }

  // 点击选择收款订单
  void onSelectedIncomeOrder(String id) {
    if (state.selectedIncomeOrderIds.contains(id)) {
      state.selectedIncomeOrderIds.remove(id);
    } else {
      state.selectedIncomeOrderIds.add(id);
    }
  }

  // 点击选择付款订单
  void onSelectedPaidOrder(String id) {
    if (state.selectedPaidOrderIds.contains(id)) {
      state.selectedPaidOrderIds.remove(id);
    } else {
      state.selectedPaidOrderIds.add(id);
    }
  }

  // 显示收款订单时间选择器
  void showIncomeDateTimePicker() {
    showDateRangePicker(
      context: Get.context!,
      firstDate: DateTime.fromMillisecondsSinceEpoch(0),
      lastDate: DateTime.now(),
      initialDateRange: DateTimeRange(
        start: DateTime.fromMillisecondsSinceEpoch(
            state.incomeOrderStartTime.value),
        end:
            DateTime.fromMillisecondsSinceEpoch(state.incomeOrderEndTime.value),
      ),
      locale: const Locale('zh', 'CN'),
    ).then((value) {
      if (value != null) {
        state.incomeOrderStartTime.value = value.start.millisecondsSinceEpoch;
        state.incomeOrderEndTime.value = value.end.millisecondsSinceEpoch;
        getCaseIncomeOrders(() {});
      }
    });
  }

  // 显示付款订单时间选择器
  void showPaidDateTimePicker() {
    showDateRangePicker(
      context: Get.context!,
      firstDate: DateTime.fromMillisecondsSinceEpoch(0),
      lastDate: DateTime.now(),
      initialDateRange: DateTimeRange(
        start:
            DateTime.fromMillisecondsSinceEpoch(state.paidOrderStartTime.value),
        end: DateTime.fromMillisecondsSinceEpoch(state.paidOrderEndTime.value),
      ),
      locale: const Locale('zh', 'CN'),
    ).then((value) {
      if (value != null) {
        state.paidOrderStartTime.value = value.start.millisecondsSinceEpoch;
        state.paidOrderEndTime.value = value.end.millisecondsSinceEpoch;
        getCasePaidOrders(() {});
      }
    });
  }

  void addIncomeOrders() async {
    EasyLoading.show(status: '关联收款订单中...');

    for (var orderId in state.selectedIncomeOrderIds) {
      await apiService.caseOrderAction(
        'add',
        id,
        orderId,
        state.unselectIncomeOrders
                .firstWhere((element) => element.id == orderId)
                .orderAmount ??
            0,
      );
    }

    _getCaseInfo(id);
    EasyLoading.dismiss();
    Get.back();
    Get.snackbar('提示', '关联收款订单成功');
  }

  void addPaidOrders() async {
    EasyLoading.show(status: '关联付款订单中...');

    for (var orderId in state.selectedPaidOrderIds) {
      await apiService.caseOrderAction(
        'add',
        id,
        orderId,
        state.unselectPaidOrders
                .firstWhere((element) => element.id == orderId)
                .orderAmount ??
            0,
      );
    }

    _getCaseInfo(id);
    EasyLoading.dismiss();
    Get.back();
    Get.snackbar('提示', '关联付款订单成功');
  }

  void _getCaseInfo(String id) {
    state.isLoading.value = true;
    apiService.getCaseDetail(id).then((value) => {
          state.isLoading.value = false,
          if (value != null)
            {
              state.caseDetail.value = value,
              if (caseStatus.keys
                  .toList()
                  .sublist(0, 3)
                  .contains(value.caseInfo!.caseStatus))
                {
                  state.caseStatus.value = 0,
                }
              else
                {
                  state.caseStatus.value = 1,
                },
              _setCaseInfoList(state.caseDetail.value!.caseInfo!),
              _setCasePersonList(state.caseDetail.value!.caseInfo!),
              _setApproveList(state.caseDetail.value!.approveList ?? []),
              _setContactFiles(state.caseDetail.value!.contractFiles ?? []),
              _setIncomeOrders(state.caseDetail.value!.orders ?? []),
              _setPaidOrders(state.caseDetail.value!.remitOrders ?? []),
            }
        });
  }

  void _setCaseInfoList(CaseDetailInfo caseInfo) {
    state.caseInfoList.clear();
    state.caseInfoList.add(CaseDetailSubItemInfo(
        title: '案件状态：',
        content: caseStatus[caseInfo.caseStatus] ?? '',
        contentColor:
            caseStatusColors[caseInfo.caseStatus] ?? AppColor.colorFontBlack));
    state.caseInfoList.add(CaseDetailSubItemInfo(
        title: '案件号：',
        content: caseInfo.id ?? '',
        contentColor: AppColor.colorFontBlack));
    state.caseInfoList.add(CaseDetailSubItemInfo(
        title: '案件名称：',
        content: caseInfo.caseNameStr ?? '',
        contentColor: AppColor.colorFontBlack));
    state.caseInfoList.add(CaseDetailSubItemInfo(
        title: '案件类型：',
        content: caseInfo.caseTypeStr ?? '',
        contentColor: AppColor.colorFontBlack));
    state.caseInfoList.add(CaseDetailSubItemInfo(
        title: '负责人',
        content: caseInfo.takerStr ?? '',
        contentColor: AppColor.colorFontBlack));
  }

  void _setCasePersonList(CaseDetailInfo caseInfo) {
    state.casePersonList.clear();
    CaseOrderInfoEntity casePersons =
        CaseOrderInfoEntity.fromJson(jsonDecode(caseInfo.archive ?? '{}'));

    state.casePersonList.add(CaseDetailItemInfo(
        title: '委托人${casePersons.caseClientList!.isNotEmpty ? '1' : ''}',
        subItemList: [
          CaseDetailSubItemInfo(
              title: '委托人名称', content: caseInfo.clientName ?? ''),
          CaseDetailSubItemInfo(
              title: '信用代码或证件号', content: caseInfo.clientCode ?? ''),
        ]));

    state.casePersonList.addAll(List.generate(
      casePersons.caseClientList!.length,
      (index) => CaseDetailItemInfo(
        title: '委托人${index + 2}',
        subItemList: [
          CaseDetailSubItemInfo(
              title: '委托人名称',
              content: casePersons.caseClientList![index].name ?? ''),
          CaseDetailSubItemInfo(
              title: '信用代码或证件号',
              content: casePersons.caseClientList![index].code ?? ''),
        ],
      ),
    ));

    state.casePersonList.add(CaseDetailItemInfo(
        title: '利益相对方${casePersons.caseOppositeList!.isNotEmpty ? '1' : ''}',
        subItemList: ((caseInfo.oppositeName.isBlank ?? true) ||
                caseInfo.oppositeName! == '<无>')
            ? []
            : [
                CaseDetailSubItemInfo(
                    title: '利益相对方名称', content: caseInfo.oppositeName ?? ''),
                CaseDetailSubItemInfo(
                    title: '信用代码或证件号', content: caseInfo.oppositeCode ?? ''),
              ]));

    state.casePersonList.addAll(List.generate(
      casePersons.caseOppositeList!.length,
      (index) => CaseDetailItemInfo(
        title: '利益相对方${index + 2}',
        subItemList: [
          CaseDetailSubItemInfo(
              title: '利益相对方名称',
              content: casePersons.caseOppositeList![index].name ?? ''),
          CaseDetailSubItemInfo(
              title: '信用代码或证件号',
              content: casePersons.caseOppositeList![index].code ?? ''),
        ],
      ),
    ));

    state.casePersonList.add(CaseDetailItemInfo(
        title: '第三方${casePersons.caseThirdList!.isNotEmpty ? '1' : ''}',
        subItemList: ((caseInfo.thirdName.isBlank ?? true) ||
                caseInfo.thirdName! == '<无>')
            ? []
            : [
                CaseDetailSubItemInfo(
                    title: '第三方名称', content: caseInfo.thirdName ?? ''),
                CaseDetailSubItemInfo(
                    title: '信用代码或证件号', content: caseInfo.thirdCode ?? ''),
              ]));

    state.casePersonList.addAll(List.generate(
      casePersons.caseThirdList!.length,
      (index) => CaseDetailItemInfo(title: '第三方${index + 2}', subItemList: [
        CaseDetailSubItemInfo(
            title: '第三方名称',
            content: casePersons.caseThirdList![index].name ?? ''),
        CaseDetailSubItemInfo(
            title: '信用代码或证件号',
            content: casePersons.caseThirdList![index].code ?? ''),
      ]),
    ));
  }

  void _setApproveList(List<CaseApproveRecord> approveList) {
    state.caseApproveList.clear();
    state.caseApproveList.addAll(approveList);
  }

  void _setContactFiles(List<CaseContractFile> contacts) {
    state.caseContractList.clear();
    state.caseContractList.addAll(contacts);
  }

  void _setIncomeOrders(List<CaseOrder> orders) {
    state.incomeOrderList.clear();
    state.incomeOrderList.addAll(orders);
    for (var item in state.incomeOrderList) {
      item.invoiceInfo =
          CaseInvoiceEntity.fromJson(jsonDecode(item.invoice ?? '{}'));
    }

    state.totalPaid.value = state.incomeOrderList.fold(
        0.0,
        (previousValue, element) =>
            previousValue + (element.orderAmount ?? 0).toDouble());
    state.deposit.value = state.incomeOrderList.fold(
        0.0,
        (previousValue, element) =>
            previousValue + (element.marginAmount ?? 0).toDouble());
  }

  void _setPaidOrders(List<CaseOrder> orders) {
    state.paidOrderList.clear();
    state.paidOrderList.addAll(orders);
    for (var item in state.paidOrderList) {
      item.invoiceInfo =
          CaseInvoiceEntity.fromJson(jsonDecode(item.invoice ?? '{}'));
    }
  }
}
